package com.haidechizi.util.lock.event;

import com.haidechizi.util.lock.annotation.Lock;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

/**
 * @author: wangdejun
 * @create: 2019-12-10 20:43
 **/
@Component
public class LockEventManager {

    private Collection<LockListener> lockListeners;

    public void addListener(LockListener lockListener) {
        if (lockListeners == null) {
            lockListeners = new HashSet<>(4);
        }
        lockListeners.add(lockListener);
    }


    public void removeListener(LockListener lockListener) {
        if (lockListeners == null) {
            return;
        }
        lockListeners.remove(lockListener);
    }


    public void beforeLock(ProceedingJoinPoint joinPoint, Lock lock) {
        if (lockListeners == null) {
            return;
        }
        LockContext lockContext = new LockContext(this, lock, joinPoint);
        Iterator<LockListener> iterator = lockListeners.iterator();
        while (iterator.hasNext()) {
            LockListener lockListener = iterator.next();
            lockListener.beforeLock(lockContext);
        }
    }


    public void afterLock(ProceedingJoinPoint joinPoint, Lock lock, Throwable throwable) {
        if (lockListeners == null) {
            return;
        }
        LockContext lockContext = new LockContext(this, lock, joinPoint);
        Iterator<LockListener> iterator = lockListeners.iterator();
        while (iterator.hasNext()) {
            LockListener lockListener = iterator.next();
            lockListener.afterLock(lockContext, throwable);
        }
    }
}
